package com.learn.sb.reactiveredis.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.sb.reactiveredis.entity.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping(value = "/webflux")
public class WebFluxController {

	@Autowired
	private ReactiveRedisTemplate reactiveRedisTemplate;

	@Autowired
	private ObjectMapper objectMapper;

	@GetMapping("/cityid/{id}")
	public Mono<City> findByCityid(@PathVariable Long id) {
		String key = "city_" + id;

		Mono<City> city =
				reactiveRedisTemplate.opsForValue(RedisSerializationContext.string()).get(key)
						.map(c -> translate(c));

		System.out.println(key);
		System.out.println(city.toString());
		return city;
	}

	public City translate(Object c) {
		// Json字符串 转 对象
		try {
			System.out.println(c);
			return objectMapper.readValue((String)c, City.class);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * postman 发送请求，参数一定要json格式
	 * http://localhost:28080/webflux/insertcity
	 * {"id":1, "cityName":"Beijing"}
	 * @param city
	 * @return
	 */
	@PostMapping("/insertcity")
	public Mono<Boolean> saveCity(@RequestBody City city) throws Exception {
		String key = "city_" + city.getId();
		String cityStr = objectMapper.writeValueAsString(city);  //对象转Json字符串
		Mono<Boolean> res = reactiveRedisTemplate.opsForValue(RedisSerializationContext.string()).set(key, cityStr);
		return res;
	}

}
